package com.ff.sms.engine.executor;

import com.alibaba.fastjson.JSONObject;
import com.ff.sms.engine.entity.Msg;
import com.ff.sms.engine.entity.MsgTemplate;
import com.ff.sms.engine.entity.consts.ClueChannel;
import com.ff.sms.engine.entity.enums.ClueTypeEnum;
import com.ff.sms.engine.entity.vo.ClueVO;
import com.ff.sms.engine.service.Dh3tSmsService;
import com.ff.sms.engine.service.MsgService;
import com.ff.sms.engine.service.MsgTplService;
import com.ff.sms.engine.util.RedisUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SmsEngineJob {

    private static final String clueQueueKey = "clue_data_key: clue:origin:data";
    private static final String havalWeixin = "http://www.haval.com.cn/";
    private static final String havalApp = "http://www.haval.com.cn/";

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    MsgService msgService;
    @Autowired
    MsgTplService msgTplService;
    @Autowired
    Dh3tSmsService dh3tSmsService;

    @XxlJob("ClueMatchingHandler")
    public ReturnT<String> clueMatchingHandler(String param) throws Exception {
        XxlJobLogger.log("ClueMatchingHandler start");

        // 只要有待处理线索，就持续处理
        String clue = (String) redisUtil.rPop(clueQueueKey);
        while (clue != null) {
            try {

                ClueVO clueVO = JSONObject.parseObject(clue, ClueVO.class);
                boolean result = process(clueVO);
                if (result) {
                    XxlJobLogger.log(String.format("线索" + clueVO.getClueOriginId().toString() + "处理完成"));
                } else {
                    XxlJobLogger.log(String.format("线索" + clueVO.getClueOriginId().toString() + "处理失败"));
                }

            } catch (Exception e) {
                XxlJobLogger.log(e);
            }
            clue = (String) redisUtil.rPop(clueQueueKey);
        }

        XxlJobLogger.log("ClueMatchingHandler finished");
        return ReturnT.SUCCESS;
    }

    private boolean process(ClueVO clueVO) {
        // 获取线索对应的短信模版类型
        ClueTypeEnum clueTypeEnum = getClueType(clueVO);

        if (clueTypeEnum != null) {
            // 匹配短信模版，构建短信
            List<MsgTemplate> tplList = msgTplService.getMsgTpl(clueTypeEnum.getCode());
            if (tplList != null && tplList.size() > 0) {
                MsgTemplate msgTemplate = tplList.get(0);
                String tplContent = msgTemplate.getTplContent();

                String shortUrl = "";
                if (StringUtils.isNotBlank(tplContent)) {
                    if (tplContent.contains("{haval_weixin}")) {
                        shortUrl = dh3tSmsService.getShortUrl(havalWeixin, 5);
                        if (StringUtils.isBlank(shortUrl)) {
                            XxlJobLogger.log("短链接生成失败，url：" + havalWeixin);
                            return false;
                        }
                        tplContent = tplContent.replace("{haval_weixin}", shortUrl);
                    } else if (tplContent.contains("{haval_app}")) {
                        shortUrl = dh3tSmsService.getShortUrl(havalApp, 5);
                        if (StringUtils.isBlank(shortUrl)) {
                            XxlJobLogger.log("短链接生成失败，url：" + havalApp);
                            return false;
                        }
                        tplContent = tplContent.replace("{haval_weixin}", shortUrl);
                    }
                }

                Msg msg = new Msg();
                msg.setPhone(clueVO.getContact());
                msg.setClueOrigiId(clueVO.getClueOriginId());
                msg.setMsgContent(tplContent);
                msg.setTplId(msgTemplate.getTplId());
                msg.setShortUrl(shortUrl);
                msg.setSendStatus(0);
                msgService.save(msg);
            }
        }
        return true;
    }

    private ClueTypeEnum getClueType(ClueVO clueVO) {
        ClueTypeEnum clueTypeEnum = null;
        // 获取线索对应的模版类型
        if (ClueChannel.OFFICIAL_PLATFORM.equals(clueVO.getTypeName())) {
            switch (clueVO.getChannel()) {
                case ClueChannel.OFFICIAL_WEB_GWM:
                case ClueChannel.OFFICIAL_WEB_HAVAL:
                case ClueChannel.OFFICIAL_WEB_WEY:
                case ClueChannel.OFFICIAL_WEB_ORA:
                case ClueChannel.OFFICIAL_WEB_PICKUP:
                    switch (clueVO.getSubChannel()) {
                        case ClueChannel.OFFICIAL_ACTIVITIES:
                            clueTypeEnum = ClueTypeEnum.ACTIVITIES;
                            break;
                        case ClueChannel.OFFICIAL_TRIAL:
                            clueTypeEnum = ClueTypeEnum.TRIAL;
                            break;
                        case ClueChannel.OFFICIAL_OPERATOR_SERVICE:
                        case ClueChannel.OFFICIAL_WEB_GWM:
                            clueTypeEnum = ClueTypeEnum.ENQUIRY;
                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }
        }
        return clueTypeEnum;
    }
}
